<?php
namespace app\admin\model;
use cubox\Model;
use cubox\model\Tree;
use app\admin\library\User;

class UserGroup extends Model
{
    use Tree;

    public function __construct()
    {
        $this->treeCacheName = $this->table.'_tree';
    }

    /**
     * 获取分组权限信息
     * @param int $group_id
     * @return array
     * 
     * 返回  ['power','extend','title']
     * 会递归合并当前分组和父分组的权限信息
     * 
     */
    public function power(int $group_id):array{
        
        $data = $this->getId($group_id);

        $power = '';
        $powerExtend = [];
        $title  = [];
        if ($data){

            if ($data['power']!='ALL'){
                $power = $data['power'];
                try{
                    if ($data['power_extend']!='') $powerExtend = json_decode($data['power_extend'],true);
                }catch(\Exception $e){
                    $powerExtend = array();
                }

                $title [] = $data['title'];
                
                if ($data['parent_id']!=0){
                    $parentPower = $this->power($data['parent_id']);
                    if ($parentPower['power']!=''){

                        if ($power!=''){
                            $power = $power.','.$parentPower['power'];
                        }else{
                            $power = $parentPower['power'];
                        }
                         
                    } 
                    $powerExtend = User::mergeExtend($parentPower['extend'],$powerExtend);
                    $title =   array_merge($parentPower['title'],$title);
                }
            }
        }

        return ['power'=>$power,'extend'=> $powerExtend,'title'=>$title];
    }


     
}